package com.ruoyi.web.controller.credit;

import java.util.List;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.CreditServiceConfig;
import com.ruoyi.system.domain.CreditUserInfo;
import com.ruoyi.system.service.ICreditServiceConfigService;
import com.ruoyi.system.service.ICreditUserInfoService;

/**
 * 信用生活服务Controller
 * 
 * @author ruoyi
 * @date 2025-01-28
 */
@RestController
@RequestMapping("/credit/lifeService")
public class CreditLifeServiceController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(CreditLifeServiceController.class);
    
    @Autowired
    private ICreditServiceConfigService creditServiceConfigService;

    @Autowired
    private ICreditUserInfoService creditUserInfoService;

    /**
     * 查询信用生活服务列表
     */
    @PreAuthorize("@ss.hasPermi('credit:lifeService:view')")
    @GetMapping("/list")
    public AjaxResult list()
    {
        // 获取所有可用的服务配置
        List<CreditServiceConfig> serviceList = creditServiceConfigService.selectAvailableServiceConfigs();
        
        // 获取当前用户信用分
        Long userId = getUserId();
        CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
        
        Integer userScore = 600; // 默认信用分
        if (userInfo == null) {
            // 如果用户信用信息不存在，尝试自动初始化
            try {
                creditUserInfoService.initUserCreditInfo(userId, null);
                userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
                if (userInfo != null) {
                    userScore = userInfo.getCreditScore();
                }
            } catch (Exception e) {
                // 初始化失败，使用默认分数
                logger.warn("自动初始化用户信用信息失败，使用默认信用分: {}", e.getMessage());
            }
        } else {
            userScore = userInfo.getCreditScore();
        }
        
        // 为每个服务添加用户是否符合条件的标识
        for (CreditServiceConfig service : serviceList) {
            service.setRemark(userScore >= service.getRequiredScore() ? "1" : "0"); // 借用remark字段标识是否符合条件
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("serviceList", serviceList);
        result.put("userScore", userScore);
        
        return success(result);
    }

    /**
     * 获取服务详情
     */
    @PreAuthorize("@ss.hasPermi('credit:lifeService:view')")
    @GetMapping("/{serviceCode}")
    public AjaxResult getServiceDetail(@PathVariable("serviceCode") String serviceCode)
    {
        CreditServiceConfig service = creditServiceConfigService.selectCreditServiceConfigByServiceCode(serviceCode);
        if (service == null) {
            return error("服务不存在");
        }

        Long userId = getUserId();
        boolean eligible = creditServiceConfigService.checkUserServiceEligibility(userId, serviceCode);
        
        Map<String, Object> result = new HashMap<>();
        result.put("service", service);
        result.put("eligible", eligible);
        
        return success(result);
    }

    /**
     * 申请使用服务
     */
    @PreAuthorize("@ss.hasPermi('credit:lifeService:view')")
    @Log(title = "信用生活服务", businessType = BusinessType.OTHER)
    @PostMapping("/apply/{serviceCode}")
    public AjaxResult applyService(@PathVariable("serviceCode") String serviceCode)
    {
        Long userId = getUserId();
        
        // 检查用户是否符合条件
        if (!creditServiceConfigService.checkUserServiceEligibility(userId, serviceCode)) {
            return error("您的信用分不足，无法申请此服务");
        }

        CreditServiceConfig service = creditServiceConfigService.selectCreditServiceConfigByServiceCode(serviceCode);
        if (service == null) {
            return error("服务不存在");
        }

        // 根据不同服务类型进行相应处理
        String message = "";
        switch (serviceCode) {
            case "lendbook":
                message = "图书借阅服务申请成功，您可以免押金借阅图书";
                break;
            case "parking":
                message = "便捷泊车服务申请成功，您可以享受停车先享后付服务";
                break;
            case "hospital":
                message = "舒心就医服务申请成功，您可以享受就医最多付一次服务";
                break;
            case "commute":
                message = "便捷乘车服务申请成功，您可以享受公交地铁扫码乘车信用付服务";
                break;
            default:
                message = "服务申请成功";
        }

        // TODO: 这里可以添加服务申请记录到数据库的逻辑
        // TODO: 可以增加信用分奖励的逻辑

        return success(message);
    }

    /**
     * 获取我的服务申请记录
     */
    @PreAuthorize("@ss.hasPermi('credit:lifeService:view')")
    @GetMapping("/myApplications")
    public AjaxResult getMyApplications()
    {
        // TODO: 这里应该查询用户的服务申请记录
        // 目前先返回模拟数据
        
        Map<String, Object> result = new HashMap<>();
        result.put("applications", new java.util.ArrayList<>());
        
        return success(result);
    }
} 